package com.similarworld.security;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.similarworld.model.User;
import com.similarworld.service.UserService;
import com.similarworld.type.UserType;

@Service("swUserDetailsService")
public class SWUserDetailService implements UserDetailsService {

	private static final Logger logger = LoggerFactory.getLogger(SWUserDetailService.class);

	@Autowired
	UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) {

		User user = userService.getByUsername(username);

		if (user == null) {
			throw new UsernameNotFoundException("invalid_user");
		}

		List<GrantedAuthority> authorities = getGrantedAuthority(user);

		user.setAuthorities(authorities);
		String md5Password = new Md5PasswordEncoder().encodePassword(user.getPassword(), null);
		user.setPassword(md5Password);

		return user;

	}

	private List<GrantedAuthority> getGrantedAuthority(User user) {

		final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		if(UserType.ADMIN.equals(user.getType())) {
			authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		} else if(UserType.USER.equals(user.getType())) {
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		} else if(UserType.SUPERUSER.equals(user.getType())) {
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
			authorities.add(new SimpleGrantedAuthority("ROLE_SUPERUSER"));
		}

		return authorities;
	}

}
